package br.com.searchpeople.database;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import br.com.searchpeople.model.PostModel;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

public class SingletonPostBD {
	
	private List<PostModel> post_collection;
	private SearchPeopleBDOpenHelper helper;
	
	private static SingletonPostBD instance;
	
	private SingletonPostBD(Context context){
		this.post_collection = new ArrayList<PostModel>();
		helper = new SearchPeopleBDOpenHelper(context);
	}
	
	public static SingletonPostBD getInstance(Context context){
		if (instance == null) {
			instance = new SingletonPostBD(context);
		} 
		
		return instance;
	}

	private byte[] compressImage(Bitmap img) {
		ByteArrayOutputStream stream = new ByteArrayOutputStream();
		img.compress(Bitmap.CompressFormat.PNG, 100, stream);
		byte[] imageInByte = stream.toByteArray();
		
		return imageInByte;
	}
	
	public boolean addPost(PostModel post) {
		boolean flag = false;
		SQLiteDatabase db = helper.getWritableDatabase();
		
		ContentValues values = new ContentValues();
		try {
			values.put("name", post.getName());
			values.put("description", post.getDescription());
			values.put("country", post.getCountry());
			values.put("state", post.getState());
			values.put("city", post.getCity());
			values.put("phone", post.getPhone());
			values.put("email", post.getEmail());
			values.put("image", compressImage(post.getImg()));
			values.put("latitude", post.getLatitude());
			values.put("longitude", post.getLongitude());
			values.put("id_user", post.getId_user());
			db.insert("posts", null, values);
			flag = true;
		} catch (Exception e) {
			flag = false;
			Log.e("SearchPeople db", "Um erro ocorreu durante a insercao da tabela: " + e.toString(), e);
		} finally {
			db.close();
		}
		return flag;
	}
	
	public List<PostModel> getAllPosts() {
		post_collection = new ArrayList<PostModel>();
		String selectQuery = "SELECT * FROM posts;";
		SQLiteDatabase db = helper.getReadableDatabase();
		Cursor cursor = db.rawQuery(selectQuery, null);
		try {
			while (cursor.moveToNext()) {
				PostModel post = new PostModel();
				post.setId(cursor.getInt(0));
				post.setName(cursor.getString(1));
				post.setDescription(cursor.getString(2));
				post.setCountry(cursor.getString(3));
				post.setState(cursor.getString(4));
				post.setCity(cursor.getString(5));
				post.setPhone(cursor.getString(6));
				post.setEmail(cursor.getString(7));
				post.setImg(BitmapFactory.decodeByteArray(cursor.getBlob(8),0,cursor.getBlob(8).length));
				post.setLatitude(cursor.getDouble(9));
				post.setLongitude(cursor.getDouble(10));
				post.setId_user(cursor.getInt(11));
				
				post_collection.add(post);
			}
		} catch (Exception e) {
			Log.e("SearchPeople db", "Um erro ocorreu durante a busca da tabela: " + e.toString(), e);
		} finally {
			db.close();
		}
	
		return post_collection;
	}
	
	public List<PostModel> searchPosts(String name) {
		List<PostModel> found = new ArrayList<PostModel>();
		Iterator<PostModel> iterator = this.getPostCollection().iterator();
		while(iterator.hasNext()) {
			PostModel item = iterator.next();
			if (item.getName().contains(name)) {
				found.add(item);
			} 
		}
		if (found.isEmpty()) {
			return null;
		}
		return found;
	}
	
	public void deleteAllPosts() {
		post_collection = new ArrayList<PostModel>();
		String selectQuery = "DELETE FROM posts;";
		SQLiteDatabase db = helper.getWritableDatabase();
		db.execSQL(selectQuery);
		db.close();
	}
	
	public List<PostModel> getPostsByUserId(int user_id) {
		List<PostModel> aux = new ArrayList<PostModel>();
		String selectQuery = "SELECT * FROM posts WHERE user_id = " + user_id + ";";
		SQLiteDatabase db = helper.getReadableDatabase();
		Cursor cursor = db.rawQuery(selectQuery, null);
		try {
			while (cursor.moveToNext()) {
				PostModel post = new PostModel();
				post.setId(cursor.getInt(0));
				post.setName(cursor.getString(1));
				post.setDescription(cursor.getString(2));
				post.setCountry(cursor.getString(3));
				post.setState(cursor.getString(4));
				post.setCity(cursor.getString(5));
				post.setPhone(cursor.getString(6));
				post.setEmail(cursor.getString(7));
				post.setImg(BitmapFactory.decodeByteArray(cursor.getBlob(8),0,cursor.getBlob(8).length));
				post.setLatitude(cursor.getDouble(9));
				post.setLongitude(cursor.getDouble(10));
				post.setId_user(cursor.getInt(11));
				
				aux.add(post);
			}
		} catch (Exception e) {
			Log.e("SearchPeople db", "Um erro ocorreu durante a busca da tabela: " + e.toString(), e);
		} finally {
			db.close();
		}
	
		return aux;
	}
	
	public List<PostModel> getPostCollection() {
		return this.post_collection;
	}

}
